<?php

/**
 * This is the model class for table "customers".
 *
 * @property int $id
 **/
class Customer extends CActiveRecord {

    /**
 * Returns the static model of the specified AR class.
 * @param string $className active record class name.
 * @return User the static model class
 */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{customers}}';
    }

    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('email, username, password, first_name, last_name, phone_number', 'required'),
            array('username, email', 'unique'),
            array('email', 'email'),
            array('email', 'length', 'max' => 128),
            array('username, password, first_name, last_name, phone_number', 'length', 'max' => 25),
        );
    }

    /**
     * event before save a record
     *
     * @return bool
     */
    protected function beforeSave(){

            if($this->isNewRecord){
                // add date created
                $this->created = time();
                $this->salt = uniqid();
                $this->password = $this->hashPassword($this->password, $this->salt);
                $this->verify_code = $this->RandomString(10);
            }

            return true;

    }

    /**
     * event after save a record
     *
     * @return bool
     */
    protected function afterSave(){

        if($this->isNewRecord){

        }

        return true;

    }


    public function hashPassword($password, $salt){
        return md5($password.$salt);
    }

    public function validatePassword($password){
        return $this->password == $this->hashPassword($password , $this->salt);
    }
    public function RandomString($length = 10) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randomString;
    }
}